<template>
  <div class="page-container">
    <!--工具栏-->
    <div class="toolbar" style="float:left;padding-top:10px;padding-left:15px;">
      <el-form :inline="true" :model="filters" :size="size">
        <el-row style="text-align: left;">
          <el-form-item>
            <el-input v-model="filters.shopname" placeholder="所属店铺" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="filters.discount" placeholder="满减折扣" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="filters.money" placeholder="满减金额" style="width:200px"></el-input>
          </el-form-item>
          <el-form-item>
            <!-- <el-input v-model="filters.mail_free" placeholder="是否包邮"></el-input> -->
            <el-select v-model="filters.mail_free" placeholder="是否包邮" style="width:200px">
              <el-option label="包邮" value="1">包邮</el-option>
              <el-option label="不包邮" value="0">不包邮</el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="filters.startWhile" type="date" value-format="yyyy-MM-dd" placeholder="开始时间" style="width:200px"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="filters.endWhile" type="date" value-format="yyyy-MM-dd" placeholder="开始时间" style="width:200px"></el-date-picker>
          </el-form-item>

        </el-row>
        <el-row>
          <el-form-item>
            <el-date-picker v-model="filters.startTime" type="date" value-format="yyyy-MM-dd" placeholder="结束时间" style="width:200px"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-date-picker v-model="filters.endTime" type="date" value-format="yyyy-MM-dd" placeholder="结束时间" style="width:200px"></el-date-picker>
          </el-form-item>
        </el-row>


        <el-row style="text-align: left;">

          <el-form-item>
            <kt-button icon="fa fa-search" :label="$t('action.search')"  type="primary" @click="findPage(filters)"/>
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-refresh" :label="$t('action.reset')"  @click="reset" type="primary"/>
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-plus" :label="$t('action.add')"  type="primary" @click="handleAdd" />
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-power-off" label="启用"  type="primary" @click="start"/>
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-times" label="停用" type="primary" @click="stop"></kt-button>
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-link" label="关联活动商品" type="primary" @click="linkProduct"></kt-button>
          </el-form-item>
          <el-form-item>
            <kt-button icon="fa fa-link" label="关联商品" type="primary" @click="link"  @hasPerms="hasPerms" v-if="on"></kt-button>
          </el-form-item>
        </el-row>

      </el-form>
    </div>
    <div class="toolbar" style="float:right;padding-top:10px;padding-right:15px;">
      <el-form :inline="true" :size="size">
        <el-form-item>
          <el-button-group>
            <el-tooltip content="刷新" placement="top">
              <el-button icon="fa fa-refresh" @click="findPage(null)"></el-button>
            </el-tooltip>
            <el-tooltip content="列显示" placement="top">
              <el-button icon="fa fa-filter" @click="displayFilterColumnsDialog"></el-button>
            </el-tooltip>
            <el-tooltip content="导出" placement="top">
              <el-button icon="fa fa-file-excel-o"  @click="downloadExcel" ></el-button>
            </el-tooltip>
          </el-button-group>
        </el-form-item>
      </el-form>
      <!--表格显示列界面-->
      <table-column-filter-dialog ref="tableColumnFilterDialog" :columns="columns"
                                  @handleFilterColumns="handleFilterColumns">
      </table-column-filter-dialog>
    </div>
    <!--表格内容栏-->
    <cy-table :height="350"
              :data="pageResult" :columns="filterColumns"
              @findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete" ref="CyTable" @selectionChange="selectionChange">
    </cy-table>
    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="55%" :visible.sync="dialogVisible" :close-on-click-modal="false" @closed="handleClose" >
      <el-form :model="dataForm" label-width="100px" :rules="dataFormRules" ref="dataForm" :size="size"
               label-position="right" inline>
        <el-form-item label="ID" prop="id" v-if="false">
          <el-input v-model="dataForm.id" :disabled="true" auto-complete="off"></el-input>
        </el-form-item>

        <el-row>

          <el-form-item label="所属商铺" prop="shop_id">
            <!-- <el-input v-model="dataForm.shop_id"  auto-complete="off"></el-input> -->
            <el-select v-model="dataForm.shop_id" style="width: 200px" >
              <el-option
                v-for="item in shoplist"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="满减折扣" prop="discount">
            <el-input v-model="dataForm.discount"  auto-complete="off" maxlength="1"
                      onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="满减金额" prop="money">
            <el-input v-model="dataForm.money"  auto-complete="off"
                      onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" ></el-input>
          </el-form-item>

        </el-row>
        <el-row>
          <el-form-item label="是否包邮" prop="mail_free">
            <el-select v-model="dataForm.mail_free" style="width: 200px;">
              <el-option label="包邮" value="1">包邮</el-option>
              <el-option label="不包邮" value="0">不包邮</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="需要达到的订单金额" prop="full_money">
            <el-input v-model="dataForm.full_money"  auto-complete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"></el-input>
          </el-form-item>
          <el-form-item label="需要达到的订单商品数量" prop="full_nums">
            <el-input v-model="dataForm.full_nums"  auto-complete="off" onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"></el-input>
          </el-form-item>
          <el-form-item label="开始时间" prop="starttime">
            <el-date-picker  v-model="dataForm.starttime" type="date" placeholder="选择日期" style="width:200px" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endtime">
            <el-date-picker  v-model="dataForm.endtime" type="date" placeholder="选择日期" style="width:200px" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          </el-form-item>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center">
        <el-button :size="size" @click.native="dialogVisible = false">{{$t('action.cancel')}}</el-button>
        <el-button :size="size" type="primary" @click.native="submitForm" :loading="editLoading">{{$t('action.submit')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script src="//unpkg.com/element-ui@2.12.0/lib/index.js"></script>
<script>
  import PopupTreeInput from "@/components/PopupTreeInput"
  import CyTable from "@/views/Core/CyTable"
  import KtButton from "@/views/Core/KtButton"
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog"
  import { format } from "@/utils/datetime"
  import axios from 'axios'
  export default {
    components:{
      PopupTreeInput,
      CyTable,
      KtButton,
      TableColumnFilterDialog
    },
    data() {
      return {
        imgUpload:this.utils.getUpLoadHost(),
        marketid:this.$route.query.id,
        size: 'small',
        document_license:'',
        filters: {
          name: ''
        },
        on:false,

        imgs:'',
        fileList:{},
        columns: [],
        shoplist:[] ,
        filterColumns: [],
        selected:"",
        pageRequest: { pageNum: 1, pageSize: 10 },
        pageResult: {},
        dialogImageUrl: '',

        operation: false, // true:新增, false:编辑
        dialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        printPage: false,
        dialogVisibleImage:false,
        dataFormRules: {
          shop_id: [
            { required: true, message: '请选择所属商铺', trigger: 'change' }
          ],
          discount: [
            { required: true, message: '请输入满减折扣', trigger: 'blur' }
          ],
          money: [
            { required: true, message: '请输入满减金额', trigger: 'blur' }
          ],
          mail_free: [
            { required: true, message: '请选择是否包邮', trigger: 'change' }
          ],
          full_money: [
            { required: true, message: '请输入需要达到的订单金额', trigger: 'blur' }
          ],
          full_nums: [
            { required: true, message: '请输入需要达到的订单商品数量', trigger: 'blur' }
          ],
          starttime: [
            { required: true, message: '请输入开始时间', trigger: 'blur' }
          ],
          endtime: [
            { required: true, message: '请输入结束时间', trigger: 'blur' }
          ],
          status: [
            { required: true, message: '请选择状态', trigger: 'change' }
          ],

        },
        dataForm: {

        },
        deptData: [],
        deptTreeProps: {
          label: 'name',
          children: 'children'
        },
        roles: [],
        ruleForm: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
      }
    },
    methods: {
      // 获取分页数据
      findPage: function (data) {
        this.filters.t='marketFullReduction'
        this.$refs.CyTable.findPage(this.filters)
      },
      // 初始化
      queryUserList(){
        var that=this;
        this.utils.request.queryUserList({'t':'shop'},function(data){
          that.shoplist=data.data
        })
      },
      // 是否显示关联按钮
      hasPerms(){
        if(this.marketid !=null && this.marketid !=""){
          return this.on=true
        }

      },
      //弹窗关闭方法
      handleClose (){
        this.$refs.dataForm.resetFields()
      },
      //复选框选中
      selectionChange (data){
        this.selected=data.selections
      },
      //启用
      start (){
        if(this.selected.length>1 || this.selected.length==0){
          this.$message({message: '请选择一条数据', type: 'error'})
        }else{
          this.$confirm('确认启用此条数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            var this_=this
            var search={};
            search.t="marketFullReduction"
            search.status="1"
            search.id = this_.selected.map(item => item.id).toString();
            this.utils.request.editUserInfo(search,this.editStartBack)

          }).catch(() => {

          });

        }
      },
      //停用
      stop (){
        if(this.selected.length>1 || this.selected.length==0){
          this.$message({message: '请选择一条数据', type: 'error'})
        }else{
          this.$confirm('确认停用此条数据?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            var this_=this
            var search={};
            search.t="marketFullReduction"
            search.status="0"
            search.id = this_.selected.map(item => item.id).toString();
            this.utils.request.editUserInfo(search,this.editStartBack)

          }).catch(() => {

          });

        }

      },
      //回调方法
      editStartBack (data){
        if(data.code == "0000"){
          this.$message({message:"操作成功" , type:'success'});
        }else{
          this.$message({message:"操作失败" , type: 'error'});
        }
        this.findPage();
      },
      //关联活动商品
      linkProduct (){
        if(this.selected.length>1 || this.selected.length==0){
          this.$message({message: '请选择一条数据', type: 'error'})
        }else{
          //跳转到商品页面进行关联
          // this.$router.push({
          // path: '/pages/configuration/shuffling',
          // query:{id:this.selected[0].id}
          // });
          this.$router.push({ path:'/product/productEntry',query:{killid: this.selected[0].id}})
        }

      },
      // link (){
      // 	if(this.selected.length==0){
      // 		this.$message({message: '请选择一条数据', type: 'error'})
      // 	}else{
      // 		//跳转到原页面
      // 		this.$message({message: '操作成功', type: 'success'})
      // 		this.$router.push({
      // 		path: '/paje/MarketNewuser'
      // 		})
      // 	}
      // },
      // 批量删除
      handleDelete: function (data) {
        var ids='';
        for(var i=0;i<data.params.length;i++){
          ids=ids+data.params[i].id+',';
        }
        data.t='marketFullReduction'
        data.ids=ids
        this.utils.request.deleteUserInfo(data,this.deleteInfoBack)
      },
      //删除callback
      deleteInfoBack(data){
        if(data.code == '0000') {
          this.$message({ message: '操作成功', type: 'success' })
        } else {
          this.$message({message: '操作失败, ', type: 'error'})
        }
        this.findPage();
      },

      //导入方法
      importexe(){
        this.printPage=true;
      },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      //列表下载
      downloadExcel() {
        this.$confirm('确定下载列表文件?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let filename="满减活动"
          this.$refs.CyTable.exportData(this.filters,this.filterColumns,filename)
        }).catch(() => {

        });
      },
      // 显示新增界面
      handleAdd: function () {
        this.dialogVisible = true
        this.operation = true
        this.dataForm.id="";
        //this.dataForm={};
        if (this.$refs['dataForm']!=undefined) {
          this.$refs['dataForm'].resetFields();
        }
        this.dataForm.document_license="";
      },
      // 打印
      print:function(){
        this.printPage=true
        this.operation = true
      },
      reset:function(){
        this.filters={};
        this.findPage()
      },

      // 显示编辑界面
      handleEdit: function (params) {
        console.log(params)
        this.dialogVisible = true
        this.operation = false
        var this_ = this;
        this.$nextTick(function(){
          this_.dataForm = Object.assign({}, params.row);
        });
        this_.dataForm.status=params.row.status
      },
      // 编辑
      submitForm: function () {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              var this_ = this;
              this.editLoading = true
              let params = Object.assign({}, this.dataForm)
              params.t='marketFullReduction';
              this.utils.request.editUserInfo(params,this.editInfoBack)
            })
          }
        })
      },
      // 新增修改回调
      editInfoBack: function (data) {
        if(data.code == '0000') {
          this.$message({ message: '操作成功', type: 'success' })
        } else {
          this.$message({message: '操作失败', type: 'error'})
        }
        this.findPage();
        this.dialogVisible = false
        this.operation = false
        this.editLoading= false
      },


      // 时间格式化
      dateFormat: function (row, column, cellValue, index){
        return format(row[column.property])
      },

      // 处理表格列过滤显示
      displayFilterColumnsDialog: function () {
        this.$refs.tableColumnFilterDialog.setDialogVisible(true)
      },
      // 处理表格列过滤显示
      handleFilterColumns: function (data) {
        this.filterColumns = data.filterColumns
        this.$refs.tableColumnFilterDialog.setDialogVisible(false)
      },
      // 处理表格列过滤显示
      initColumns: function () {
        this.columns = [
          //{prop:"id", label:"ID", minWidth:50},
          {prop:"shopname", label:"所属商铺", minWidth:120},
          {prop:"discount", label:"满减折扣", minWidth:120},
          {prop:"money", label:"满减金额", minWidth:120},
          {prop:"mail_free", label:"是否包邮", minWidth:120,formatter:this.fomfree},
          {prop:"full_money", label:"需要达到的订单金额", minWidth:120},
          {prop:"full_nums", label:"需要达到的订单商品数量", minWidth:120},
          {prop:"starttime", label:"开始时间", minWidth:120},
          {prop:"endtime", label:"结束时间", minWidth:120},
          {prop:"status", label:"状态", minWidth:120,formatter:this.status},
          {prop:"create_time", label:"创建时间", minWidth:120},
        ]
        var temp = [];
        $.each(this.columns,function(key, val){
          temp.push(val)
        })
        this.filterColumns = temp;
      },
      status: function(row, column, cellValue, index){
        if(cellValue==1){
          return '生效'
        }else if(cellValue==0){
          return '失效'
        }
      },
      fomfree: function(row, column, cellValue, index){
        if(cellValue==1){
          return '包邮'
        }else if(cellValue==0){
          return '不包邮'
        }
      },


    },
    mounted() {
      this.findPage()
      this.initColumns()
      this.queryUserList()
      this.hasPerms()
    }

  }
</script>

<style scoped>
  /deep/ .el-input__inner {
        width: 200px;
  }
   .el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
        margin-bottom: 10px;
  }

</style>
